package com.lcifn.middleware.rpc.serializer.hessian;

import com.caucho.hessian.io.Hessian2Input;
import com.caucho.hessian.io.Hessian2Output;
import com.caucho.hessian.io.HessianHandle;
import com.caucho.hessian.io.HessianInputFactory;
import com.lcifn.middleware.rpc.serializer.Serializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

/**
 * Title: HessianSerializer.java<br>
 * Description: <br>
 * Copyright: Copyright (c) 2021<br>
 * Company: 北京云杉世界信息技术有限公司<br>
 *
 * @author LC
 * @date 2021/2/22 14:03
 */
public class HessianSerializer <T> implements Serializer<T> {

    /**
     * 序列化对象，将对象转化为字节数组
     *
     * @param entry
     * @return
     */
    @Override
    public byte[] serialize(T entry) {
        byte[] result = null;
        try {
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            Hessian2Output output = new Hessian2Output(os);
            output.writeObject(entry);
            output.flush();
            result = os.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException(String.format("Class %s serialize occupy error. ", entry.getClass().getCanonicalName()), e);
        }
        return result;
    }

    /**
     * 反序列化
     *
     * @param bytes
     * @param clazz
     * @return
     */
    @Override
    public T deserialize(byte[] bytes, Class<T> clazz) {
        Object result = null;
        try {
            ByteArrayInputStream is = new ByteArrayInputStream(bytes);
            Hessian2Input input = new Hessian2Input(is);
            result = input.readObject(clazz);
        } catch (IOException e) {
            throw new RuntimeException(String.format("Class %s deserialize occupy error. ", clazz.getCanonicalName()), e);
        }
        return (T) result;
    }

    /**
     * 返回序列化对象类型的Class对象。
     */
    @Override
    public Class<T> getSerializeClass() {
        return null;
    }
}
